import './GlobalHeader.css'
import { useNavigate } from 'react-router-dom';
import { Button, Dropdown, message, Switch } from 'antd';
import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import { userLogout } from '../api/user.js';
import { useUserStore } from '../store/user.js';
import { defaultAvatar } from '../constant/index.js';
import { useState, useEffect } from 'react';
export default function Navbar() {

    const user = useUserStore(state => state.user);
    const isLogin = useUserStore(state => state.isLogin);
    const hasHydrated = useUserStore(state => state._hasHydrated);

    // 主题状态管理
    const [isDarkMode, setIsDarkMode] = useState(() => {
        // 从localStorage读取主题设置，默认为false（白天模式）
        const savedTheme = localStorage.getItem('theme');
        return savedTheme === 'dark';
    });

    // 等待hydration完成
    if (!hasHydrated) {
        return <div>加载中...</div>; // 或返回骨架屏等
    }

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 主题切换函数
    const toggleTheme = () => {
        const newTheme = !isDarkMode;
        setIsDarkMode(newTheme);
        localStorage.setItem('theme', newTheme ? 'dark' : 'light');

        // 切换body的class来应用主题
        if (newTheme) {
            document.body.classList.add('dark-theme');
            document.body.classList.remove('light-theme');
        } else {
            document.body.classList.add('light-theme');
            document.body.classList.remove('dark-theme');
        }
    };

    // 组件挂载时应用主题
    useEffect(() => {
        if (isDarkMode) {
            document.body.classList.add('dark-theme');
            document.body.classList.remove('light-theme');
        } else {
            document.body.classList.add('light-theme');
            document.body.classList.remove('dark-theme');
        }
    }, [isDarkMode]);


    // 基础导航菜单
    const baseNavContent = [
        {
            title: '生成器',
            icon: '/src/assets/生成代码.png',
            path: '/'
        },
        {
            title: '提示词库',
            icon: '/src/assets/数据字典.png',
            path: '/dict'
        },
        {
            title: '关于',
            icon: '/src/assets/关于.png',
            path: '/about'
        }
    ];

    // 根据用户角色决定显示的导航菜单
    const navContent = baseNavContent;


    const handleLogout = async () => {
        const res = await userLogout();

        if (res?.data?.code === 0) {
            messageApi.success('退出登录')
            useUserStore.getState().logout();
            setTimeout(() => {
                navigate('/user/login', { replace: true })
            }, 1000)
        } else {
            messageApi.error('退出登录失败')
        }

    }

    const items = [
        {
            key: 'center',
            label: (
                <div onClick={() => navigate('/user/info')}>
                    个人中心
                </div>)
        },
        {
            key: 'logout',
            label: (
                <div onClick={handleLogout}>
                    退出登录
                </div>
            ),
        },
    ];




    return (
        <div id='GlobalHeader'>
            {contextHolder}
            <div className='logo'>
                <img src="/src/assets/logo.jpg" alt="logo" className='logo-img' />
                <div className='logo-title'>AI 提示词</div>
            </div>
            <div className='nav'>

                {navContent.map((item, index) => (
                    <div key={index} className='nav-item' onClick={() => {
                        navigate(item.path)
                    }}>
                        <img src={item.icon} alt={item.title} width={16} />
                        <span style={{ marginLeft: '4px' }}>{item.title}</span>
                    </div>
                ))}

                {/* <div className='nav-item'>
                    <img src="/src/assets/生成代码.png" alt="maker" width={16} />
                    <span style={{ marginLeft: '4px' }}>生成器</span>
                </div>

                <div className='nav-item'>
                    <img src='/src/assets/数据字典.png' alt='dict' width={14} />
                    <span style={{ marginLeft: '4px' }}>提示词库</span>
                </div>

                <div className='nav-item'>
                    <img src='/src/assets/关于.png' alt='dict' width={16} />
                    <span style={{ marginLeft: '4px' }}>关于</span>
                </div> */}
            </div>
            <div className='user'>
                {/* 主题切换按钮 */}
                <div className='theme-switch'>
                    <Switch
                        checked={isDarkMode}
                        onChange={toggleTheme}
                        checkedChildren={<MoonOutlined />}
                        unCheckedChildren={<SunOutlined />}
                        style={{ marginRight: '16px' }}
                    />
                </div>

                {
                    isLogin ? (
                        <Dropdown menu={{ items }} placement="bottom" arrow>
                            <div className='user-info'>
                                <img src={user.userAvatar || defaultAvatar} alt="user-avatar" className='user-avatar' />
                                <div className='username'>{user.userName || '匿名'}</div>
                            </div>
                        </Dropdown>
                    ) : (
                        <Button className='user-info' type='primary' onClick={() => { navigate('/user/login') }}>
                            登录
                        </Button>
                    )
                }

            </div>
        </div >
    )
}